package com.love.data.structure.queues;

/**
 * 队列
 * 基于数组
 *
 * @author love
 * @version 1.0
 * @date 2021/9/22
 */
public class Queues {

    /**
     * 队列默认的大小
     */
    private static final int MAX_SIZE = 16;
    /**
     * 队列最大
     */
    private final int maxSize;
    /**
     * 队列的实际数组实现
     */
    private final int[] queueArray;
    /**
     * 头
     */
    private int header;
    /**
     * 尾
     */
    private int end;
    /**
     * 元素个数
     */
    private int nItems;

    public Queues() {
        this(MAX_SIZE);
    }

    /**
     * 初始化
     *
     * @param size 大小
     * @author gd liu
     * @date 2021/9/22 10:49
     */
    public Queues(int size) {
        maxSize = size;
        queueArray = new int[size];
        header = 0;
        end = -1;
        nItems = 0;
    }

    /**
     * 添加元素
     *
     * @param item 元素
     * @return boolean
     * @author gd liu
     * @date 2021/9/22 10:24
     */
    public boolean add(int item) {
        if (isFull()) {
            return false;
        }
        nItems++;
        end = (end + 1) % maxSize;
        queueArray[end] = item;
        return true;
    }

    /**
     * 删除元素
     *
     * @return boolean
     * @author gd liu
     * @date 2021/9/22 10:31
     */
    public boolean remove() {
        if (isEmpty()) {
            return false;
        }
        nItems--;
        header = (header + 1) % maxSize;
        return true;
    }

    /**
     * 获取元素个数
     *
     * @return int
     * @author gd liu
     * @date 2021/9/22 10:18
     */
    public int size() {
        return nItems;
    }

    /**
     * 判断队列是否空了
     *
     * @return boolean
     * @author gd liu
     * @date 2021/9/22 10:26
     */
    public boolean isEmpty() {
        return nItems == 0;
    }

    /**
     * 判断队列是否满了
     *
     * @return boolean
     * @author gd liu
     * @date 2021/9/22 10:19
     */
    public boolean isFull() {
        return nItems == maxSize;
    }

    @Override
    public String toString() {
        StringBuilder queueArrayStr = new StringBuilder("[");
        for (int i = header; ; i = ++i % maxSize) {
            if (i == end) {
                break;
            }
            queueArrayStr.append(queueArray[i]).append(",");
        }
        queueArrayStr.deleteCharAt(queueArrayStr.length() - 1);
        queueArrayStr.append("]");
        return "Queues{" +
                "queues=" + queueArrayStr +
                ", header=" + header +
                ", end=" + end +
                ", nItems=" + nItems +
                '}';
    }
}
